<template>
	<view class="page">
		<!-- 顶部统计区域（改为：上次跑步所在月份的统计） -->
		<view class="stats">
			<view class="stats-row">
				<view class="stats-col">
					<view class="num">{{ monthSummary.times }}</view>
					<view class="label">{{ monthLabel }} 跑步次数</view>
				</view>
				<view class="stats-col center">
					<view class="num big">{{ monthSummary.steps }}</view>
					<view class="label">{{ monthLabel }} 累计步数</view>
				</view>
				<view class="stats-col">
					<view class="num">{{ monthSummary.duration }}</view>
					<view class="label">{{ monthLabel }} 总时长</view>
				</view>
			</view>
		</view>

		<!-- 内容区：上次跑步记录（取最新一条） -->
		<view class="content">
			<wd-card v-if="lastRecord" class="record-card" :use-footer-slot="true">
				<!-- 标题：日期 / 时间 -->
				<template #title>
					<text class="date">{{ lastRecord.date }} / {{ lastRecord.time }}</text>
				</template>

				<!-- 主体内容 -->
				<template #default>
					<view class="card-body">
						<view class="row">
							<view class="col">
								<text class="label">步数：</text>
								<text class="val">{{ lastRecord.steps }}</text>
							</view>
							<view class="col">
								<text class="label">用时：</text>
								<text class="val">{{ lastRecord.duration }}</text>
							</view>
						</view>
						<view class="row">
							<view class="col">
								<text class="label">平均配速：</text>
								<text class="val">{{ lastRecord.pace }}</text>
							</view>
							<!-- #ifdef MP-WEIXIN -->
							<button class="share" open-type="share" :data-id="lastRecord && lastRecord.id">
								<wd-icon name="share" size="18" />
								<text>分享</text>
							</button>
							<!-- #endif -->
						</view>
					</view>
				</template>
			</wd-card>

			<wd-divider v-else>暂无跑步记录</wd-divider>
		</view>
	</view>
</template>

<script setup>
	import {
		computed
	} from 'vue'
	import {
		useAppStore
	} from '@/stores/app'

	const store = useAppStore()

	/** —— 已有：最新一条记录 —— */
	const lastRecord = computed(() => store.lastRun || null)

	/** —— 工具：时间 & 汇总 —— */
	function parseDurationToSeconds(str) {
		if (!str) return 0
		// 兼容全角冒号
		const normalized = String(str).replace(/：/g, ':').replace(/[^\d:]/g, '')
		const [hh = '0', mm = '0', ss = '0'] = normalized.split(':')
		return (+hh) * 3600 + (+mm) * 60 + (+ss)
	}

	function secondsToHHMMSS(total) {
		const h = Math.floor(total / 3600)
		const m = Math.floor((total % 3600) / 60)
		const s = total % 60
		const pad = (n) => String(n).padStart(2, '0')
		return `${pad(h)}:${pad(m)}:${pad(s)}`
	}

	function monthKeyOf(date) {
		const y = date.getFullYear()
		const m = String(date.getMonth() + 1).padStart(2, '0')
		return `${y}-${m}` // e.g. 2025-09
	}

	function monthKeyFromDateStr(yyyy_mm_dd) {
		if (!yyyy_mm_dd) return ''
		// 允许 2025-9-1 / 2025-09-01 / 2025/09/01
		const s = String(yyyy_mm_dd).replace(/\//g, '-')
		const [y, m] = s.split('-')
		if (!y || !m) return ''
		return `${y}-${String(m).padStart(2, '0')}`
	}

	/** —— 目标月份：以 lastRecord 的月份为准；没有记录则为空 —— */
	const lastMonthKey = computed(() => {
		if (!lastRecord.value) return ''
		return monthKeyFromDateStr(lastRecord.value.date)
	})

	/** —— 友好显示：09月 / -- —— */
	const monthLabel = computed(() => {
		if (!lastMonthKey.value) return '--'
		const mm = lastMonthKey.value.slice(5)
		return `${Number(mm)}月`
	})

	/** —— 获取该月的所有记录（兼容两种 store 结构） —— */
	const monthRecords = computed(() => {
		const key = lastMonthKey.value
		if (!key) return []
		// 1) 优先 recordsByMonth
		const byMonth = store.run?.recordsByMonth?.[key]
		if (Array.isArray(byMonth)) return byMonth

		// 2) 否则从扁平 records 里筛
		const flat = store.run?.records
		if (Array.isArray(flat)) {
			return flat.filter(r => monthKeyFromDateStr(r?.date) === key)
		}
		return []
	})

	/** —— 该月汇总：次数 / 步数 / 总时长 —— */
	const monthSummary = computed(() => {
		const list = monthRecords.value
		const times = list.length
		const steps = list.reduce((s, r) => s + (Number(r?.steps) || 0), 0)
		const totalSeconds = list.reduce((s, r) => s + parseDurationToSeconds(r?.duration), 0)
		return {
			times,
			steps,
			duration: secondsToHHMMSS(totalSeconds)
		}
	})

	/** —— （保留原来的总汇总如需用）—— */
	// const summary = computed(() => store.runSummary)
</script>

<style scoped>
	.page {
		min-height: 100vh;
		background: linear-gradient(to bottom, #c4ffd5 0%, #f5f5f5 35%, #f5f5f5 100%);
	}

	/* 顶部统计：上下留白更大 */
	.stats {
		padding: 84rpx 30rpx 48rpx;
	}

	.stats-row {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
	}

	.stats-col {
		flex: 1;
		text-align: center;
	}

	.stats-col.center {
		flex: 1.5;
	}

	.num {
		font-size: 36rpx;
		font-weight: 600;
		color: #000;
		line-height: 1.2;
		margin-bottom: 30rpx;
	}

	.num.big {
		font-size: 56rpx;
		font-weight: 700;
	}

	.label {
		margin-top: 10rpx;
		font-size: 24rpx;
		color: #333;
	}

	/* 内容区与统计区的间距更舒展 */
	.content {
		padding: 40rpx 30rpx 70rpx;
	}

	/* 卡片宿主：控制外间距/圆角 */
	.record-card {
		border-radius: 20rpx;
		overflow: hidden;
		margin-top: 28rpx;
		background: #fff;
	}

	/* 穿透到 wd-card 内部容器 */
	:deep(.record-card .wd-card),
	:deep(.wd-card.record-card) {
		background: #fff;
		border: none !important;
		border-radius: 20rpx;
		overflow: hidden;
		box-shadow: 0 8px 18px rgba(0, 0, 0, 0.18), 0 18px 40px rgba(0, 0, 0, 0.22) !important;
	}

	:deep(.wd-card__header) {
		padding: 20rpx 22rpx;
	}

	:deep(.wd-card__body) {
		padding: 0 22rpx 12rpx;
	}

	/* 卡片内文字整体加大 */
	.date {
		font-size: 32rpx;
		font-weight: 700;
		color: #333;
	}

	.card-body {
		margin-top: 8rpx;
	}

	.row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 22rpx 10rpx;
		gap: 16rpx;
	}

	.col {
		display: flex;
		align-items: baseline;
		gap: 8rpx;
	}

	.label {
		font-size: 28rpx;
		color: #555;
	}

	.val {
		font-size: 34rpx;
		font-weight: 600;
		letter-spacing: 1rpx;
	}

	.share {
		display: inline-flex;
		align-items: center;
		gap: 8rpx;
		padding: 8rpx 16rpx;
		border-radius: 999rpx;
		border: 2rpx solid #cfcfcf;
		background: #fff;
		color: #444;
		line-height: 1;
		margin-left: 100rpx;
	}

	.share:active {
		background: #f5f5f5;
	}
</style>